<template>
	<view class="content bgc-f0 p60">
		<view class="p30 bgc-fff" style="border-radius: 20rpx;" id="canvasBox">
			<view class="ewm pt60 pb60">
				<view class="z-flex mb50" :style="{'width': widthBg*0.7 +'px'}">
					<u-image :src="userInfo.cover" width="100" height="100" border-radius="50"></u-image>
					<view class="z-flex z-flex-around c-fff ml20 fs24" style="flex-direction: column;">
						<text>{{userInfo.name}}</text>
						<text>{{userInfo.phone}}</text>
					</view>
				</view>
				<canvas :style="{'width': widthBg*0.7 +'px','height': widthBg*0.7 + 'px'}" canvas-id="myQrcode"></canvas>
			</view>
		</view>
		<canvas id="posterCanvas" canvas-id="posterCanvas" class="poster-canvas" :style="{'width': widthBg +'px','height': heightBg + 'px'}"></canvas>

		<view class="mt30 z-flex z-flex-justify-c">
			<u-button size="medium" shape="circle" @click="savePoster" :disabled="loading" :loading="loading">保存到本地</u-button>
		</view>

	</view>
</template>

<script>
	import drawQrcode from 'weapp-qrcode'
	import {
		getUserInfoApi
	} from '@/api/user.js'
	export default {
		data() {
			return {
				posterTempFilePath: '',
				widthBg: 0,
				heightBg: 0,
				loading: false,
				userInfo: {},
				loginStatus: uni.getStorageSync('openid'),
				userId: uni.getStorageSync('userId'),
				businessId: uni.getStorageSync('businessId')
			}
		},
		onReady() {
			// const query = uni.createSelectorQuery().in(this);
			// query.select('#canvasBox').boundingClientRect((res) => {
			// 	this.widthBg = res.width
			// 	this.heightBg = res.height
			// }).exec();
		},
		onShow() {
			this.$nextTick(()=>{
				const query = uni.createSelectorQuery().in(this);
				query.select('#canvasBox').boundingClientRect((res) => {
					this.widthBg = res.width
					this.heightBg = res.height + res.width*0.7
					this.getUserInfo()
				}).exec();
			})
		},
		methods: {
			async getUserInfo() {
				const {
					code,
					data
				} = await getUserInfoApi({
					openId: this.loginStatus
				})
				if (code != 0) return
				this.userInfo = data
				this.getQrcode()
			},
			getQrcode() {
				uni.showLoading({
					title: '二维码绘制中'
				})
				const query = this.businessId?`a=${this.userId}&b=${this.businessId}`:`a=${this.userId}`
				drawQrcode({
					width: this.widthBg * 0.7,
					height: this.widthBg * 0.7,
					canvasId: 'myQrcode',
					text: `https://cqjmc.com/jmc?${query}`,
					callback: _ => {
						uni.hideLoading()
						/* canvas画布导出图片，临时路径，供海报导出 */
						setTimeout(()=>{
							uni.canvasToTempFilePath({
								canvasId: 'myQrcode',
								success: (res) => {
									this.posterTempFilePath = res.tempFilePath
								}
							})
						},500)
					}
				})
			},
			async savePoster() {
				const that = this
				that.loading = true
				uni.showLoading({
					title: '二维码生成中'
				})
				const ctx = uni.createCanvasContext('posterCanvas', that)
				const imageUrl = await that.getNetworkImage(that.userInfo.cover)
				const space = 15
				// 画背景
				ctx.setFillStyle('white')
				ctx.fillRect(0, 0, that.widthBg, that.heightBg)
				// 画渐变色
				const grd = ctx.createLinearGradient(0, 0, 0, that.heightBg)
				grd.addColorStop(0, '#ccaf85')
				grd.addColorStop(1, '#cdc3b7')
				ctx.setFillStyle(grd)
				ctx.fillRect(space, space, that.widthBg - space * 2, that.heightBg - space * 2)
				// 填充文字
				ctx.setFontSize(12)
				ctx.setFillStyle('white')
				ctx.fillText(that.userInfo.name, 115, 62)
				ctx.fillText(that.userInfo.phone, 115, 85)
				// 画二维码
				ctx.drawImage(that.posterTempFilePath, 45, 120, that.widthBg - 90, that.widthBg - 90)
				ctx.arc(70, 70, 30, 0, 2 * Math.PI)
				ctx.fill()
				ctx.clip()
				// 画头像
				ctx.drawImage(imageUrl, 40, 40, 60, 60)
				ctx.draw(false, () => {
					try {
						uni.canvasToTempFilePath({
							canvasId: 'posterCanvas',
							success: (res) => {
								this.posterTempFilePath = res.tempFilePath;
								uni.saveImageToPhotosAlbum({
									filePath: this.posterTempFilePath,
									success: () => {
										uni.hideLoading()
										uni.showToast({
											title: '二维码保存成功',
											icon: 'success'
										});
									},
									fail: (err) => {
										uni.showModal({
											title: '图片保存失败',
											content: '请确认是否已开启授权',
											confirmText: '开启授权',
											success(res) {
												if (res.confirm) {
													uni.openSetting({
														success(settingdata) {
															if (settingdata
																.authSetting[
																	"scope.writePhotosAlbum"
																	]) {
																uni.showToast({
																	title: '授权成功，请重试哦~',
																	icon: "none"
																});
															} else {
																uni.showToast({
																	title: '请确定已打开保存权限',
																	icon: "none"
																});
															}
														}
													})
												}
											}
										})
									},
									complete: () => {
										uni.hideLoading()
										this.loading = false
									}
								})
							},
							fail: (err) => {
								uni.showToast({
									title: '二维码绘制失败',
									icon: 'none'
								})
								uni.hideLoading()
								that.loading = false
							}
						}, that);
					} catch (e) {
						uni.hideLoading()
						that.loading = false
					}

				})
			},
			// 网络图片转本地
			getNetworkImage(url) {
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url,
						success: (e) => {
							const p = e.tempFilePath
							if (p.indexOf('json') > -1) {
								reject(p)
								return false
							}
							resolve(p)
						},
						fail: (r) => {
							reject(r)
						}
					})
				})
			},
			// 以宽为基准
			aspectFit(imageWidth, imageHeight, canvasWidth, canvasHeight) {
				const imageRate = imageWidth / imageHeight
				const canvasRate = canvasWidth / canvasHeight
				let [dx, dy, dw, dh] = []
				if (imageRate >= canvasRate) {
					dw = canvasWidth
					dh = canvasWidth / imageRate
				} else {
					dh = canvasHeight
					dw = canvasHeight * imageRate
				}
				dx = (canvasWidth - dw) / 2
				dy = (canvasHeight - dh) / 2
				return [dx, dy, dw, dh]
			}
		}
	}
</script>

<style scoped lang="scss">
	.content {
		.poster-canvas {
			position: absolute;
			left: -2400rpx;
			top: 0;
		}

		.ewm {
			background: linear-gradient(180deg, #ccaf85, #cdc3b7);
			width: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;
		}
	}
</style>
